<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Imports\DomainImport;
use App\Models\Log\CashLog;
use App\Models\User\Invoice;
use App\Models\User\Recharge;
use App\Models\User\Withdrawal;
use App\Models\User\WithdrawalAccess;
use App\Traits\AliPay;
use App\Traits\Upload;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

class FundsController extends Controller
{
    use AliPay, Upload;

    public function recharge(Request $request)
    {
        if ($request->isMethod('post')) {
            $validator = Validator::make(
                $request->all(),
                [
                    'paytype' => 'required',
                    'money'   => 'required|numeric|min:10|max:50000',
                ], [
                    'paytype.required' => '支付类型错误',
                    'money.required'   => '支付类型错误',
                    'money.numeric'    => '输入金额错误',
                    'money.min'        => '最小充值 10 元',
                    'money.max'        => '最大充值 50,000 元',
                ]
            );

            if ($validator->fails()) {
                $error      = collect($validator->errors()->all());
                $returnData = array(
                    'code'  => '0',
                    'msg'   => '验证失败',
                    'data'  => $validator->errors()->first(),
                    'error' => $error->toJson(),

                );

                return response()->json($returnData, 500);
            }

            //通过验证

            // **********生成订单信息**********
            $user            = \auth('admin')->user();
            $outTrandeNo     = time().substr(md5(time().$user->id), 1, 13);
            $recharge_amount = number_format($request->get('money'));

            // **********创建订单**********
            $order_data = [
                'user_id'         => $user->id,
                'out_trade_no'    => $outTrandeNo,
                'subject'         => '会员充值',
                'recharge_amount' => $recharge_amount,
            ];
            $order      = Recharge::create($order_data);
            if ($order) {
                return $this->result_api(200, 'success', ['outTradeNo' => $outTrandeNo]);
            } else {
                return $this->result_api(400, '支付请求失败!');
            }
        }

        return view('member.funds.recharge');
    }

    public function AliPay(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'outTradeNo' => 'required|size:23',
                'type'       => 'required',
            ], [
                'outTradeNo.required' => '订单号不正确',
                'outTradeNo.size'     => '订单号不正确.',
                'type.required'       => '支付类型错误',
            ]
        );

        if ($validator->fails()) {
            $error      = collect($validator->errors()->all());
            $returnData = array(
                'code'  => '0',
                'msg'   => '验证失败',
                'data'  => $validator->errors()->first(),
                'error' => $error,

            );


            return redirect(url('/funds/recharge'))->with('message', $returnData['error'][0]);
        }

        //通过验证

        $order = Recharge::where('out_trade_no', $request->get('outTradeNo'))->first();
        if ( ! $order) {
            return redirect(url('/funds/recharge'))->with('message', '不存在的订单');
        }

        if ($order->pay_status == true && $order->total_amount > 0) {
            return redirect(url('/funds/recharge'))->with('message', '请勿重复付款');
        }
        // **********发起支付**********
        //测试
        $order->recharge_amount = 0.01; //测试

        if ($request->get('type') == 'pc') {
            $res = $this->AliPay_Pc_Pay($order->subject, $order->out_trade_no, $order->recharge_amount);
        }
        if ($request->get('type') == 'wap') {
            $res = $this->AliPay_Wap_Pay($order->subject, $order->out_trade_no, $order->recharge_amount);
        }

        if (isset($res)) {
            return $res;
        } else {
            return redirect(url('/funds/recharge'))->with('message', '支付请求失败');
        }

    }

    public function list()
    {
        //资金明细
        $request    = \request();
        $member     = auth('admin')->user();
        $queryValue = $request->get('queryValue');
        $queryType  = $request->get('queryType');
        $limit      = $request->get('limit', 10);
        if ($queryType == 'name') {
            $data = CashLog::where('user_id', $member->id)->where('name', 'like',
                '%'.$queryValue.'%')->orderBy('created_at', 'desc')->paginate($limit);
        } elseif ($queryType == 'number') {
            $data = CashLog::where('user_id', $member->id)->where('number', 'like',
                '%'.$queryValue.'%')->orderBy('created_at', 'desc')->paginate($limit);
        } else {
            $data = CashLog::where('user_id', $member->id)->orderBy('created_at', 'desc')->paginate($limit);
        }

        return view('member.funds.list', compact('data', 'queryValue', 'queryType'));
    }

    public function withdrawal(Request $request)
    {
        $user = auth('admin')->user();
        if ($request->isMethod('POST')) {
            $validator = Validator::make(
                $request->all(),
                [
                    'amount' => 'required|numeric',
                    'type'   => 'required|numeric',
                ], [
                    'amount.required' => '请输入金额',
                    'amount.numeric'  => '请输入金额',
                    'type.required'   => '请选择支付方式',
                    'type.numeric'    => '请选择支付方式',
                ]
            );

            if ($validator->fails()) {
                $error      = collect($validator->errors()->all());
                $returnData = array(
                    'code'  => '0',
                    'msg'   => '验证失败',
                    'data'  => $validator->errors()->first(),
                    'error' => $error->toJson(),

                );

                return response()->json($returnData, 500);
            }
            //验证成功

            //提现账户
            $withdrawal_access = WithdrawalAccess::where('user_id', $user->id)->where('type',
                $request->get('type'))->first();
            if ( ! $withdrawal_access) {
                return $this->result_api(200, '账号错误 error');
            }

            //余额是否充足
            $apply_amount   = round($request->get('amount'), 2); //申请金额
            $new_cash       = round($user->cash - $apply_amount, 2); //申请金额
            $service_charge = round($apply_amount * config('withdrawal.service_charge') / 100, 2);

            if ($new_cash < 0) {
                return $this->result_api(200, '余额不足');
            }

            DB::beginTransaction();
            try {
                //申请提现
                $data = [
                    'user_id'        => $user->id,
                    'name'           => $withdrawal_access->name,
                    'access'         => $withdrawal_access->access,
                    'amount'         => $apply_amount, //申请金额
                    'arrival_amount' => $apply_amount - $service_charge, //实际到账
                    'service_charge' => $service_charge,//手续费
                    'type'           => $request->get('type'),
                ];
                Withdrawal::create($data);
                //现金日志
                $cash_log_data = [
                    'user_id'      => $user->id,
                    'out_trade_no' => 0,
                    'operator'     => '[本人]',
                    'value'        => $apply_amount * -1,
                    'before'       => $user->cash,
                    'after'        => $new_cash,
                    'type'         => 13, //'支付类型 13 申请提现'
                    'remarks'      => '', //备注
                ];
                CashLog::create($cash_log_data);
                //扣除金币 (冻结)
                $user->cash = $new_cash;
                $user->save();
                //提交
                DB::commit();

                return $this->result_api(200, 'success');
            } catch (Exception $e) {
                //回滚
                DB::rollback();

                return $this->result_api(200, '参数错误 error');
            }
        }
        $withdrawal_access = WithdrawalAccess::where('user_id', $user->id)->where('type', 2)->get();

        return view('member.funds.withdrawal', compact('user', 'withdrawal_access'));
    }

    public function withdrawalList(Request $request)
    {
        $user       = \auth('admin')->user();
        $queryValue = $request->get('queryValue');
        $queryType  = $request->get('queryType');
        $limit      = $request->get('limit', 10);
        $data       = [];
        if ($queryType == 'name') {
            $data = Withdrawal::where('user_id', $user->id)->where('name', 'like',
                '%'.$queryValue.'%')->orderBy('created_at', 'desc')->paginate($limit);
        } elseif ($queryType == 'number') {
            $data = Withdrawal::where('user_id', $user->id)->where('number', 'like',
                '%'.$queryValue.'%')->orderBy('created_at', 'desc')->paginate($limit);
        } else {
            $data = Withdrawal::where('user_id', $user->id)->orderBy('created_at', 'desc')->paginate($limit);
        }

        return view('member.funds.withdrawal-list', compact('data', 'queryValue', 'queryType'));
    }

    public function withdrawalSetting(Request $request)
    {
        if ($request->isMethod('POST')) {
            $validator = Validator::make(
                $request->all(),
                [
                    'name'   => 'required',
                    'access' => 'required',
                    'type'   => 'required',
                ], [
                    'name.required'   => '收款人 必填',
                    'access.required' => '账号 必填',
                    'type.required'   => '类型错误',
                ]
            );

            if ($validator->fails()) {
                $error      = collect($validator->errors()->all());
                $returnData = array(
                    'code'  => '0',
                    'msg'   => '验证失败',
                    'data'  => $validator->errors()->first(),
                    'error' => $error->toJson(),

                );

                return response()->json($returnData, 500);
            }
            //验证成功
            $user              = auth('admin')->user();
            $withdrawal_access = WithdrawalAccess::updateOrCreate(
                [
                    'user_id' => $user->id,
                    'type'    => $request->get('type')
                ]
                , [
                    'name'   => $request->get('name'),
                    'access' => $request->get('access'),
                ]
            );
            if ($withdrawal_access) {
                return $this->result_api(200, 'success');
            } else {
                return $this->result_api(200, 'updateOrCreate error');
            }

        }

        return view('member.funds.withdrawal-setting');
    }

    public function invoice(Request $request)
    {
        if ($request->isMethod('POST')) {
            $validator = Validator::make(
                $request->all(),
                [
                    'invoice_amount'  => 'required|integer',
                    'invoice_title'   => 'required',
                    'invoice_id_num'  => 'required',
                    'receiver_email'  => 'required|email',
                    'receiver_mobile' => 'required|regex:/^1[3456789][0-9]{9}$/',
                ], [
                    'invoice_amount.required'  => '金额 必填',
                    'invoice_amount.integer'   => '金额 必须是整数',
                    'invoice_title.required'   => '抬头 必填',
                    'invoice_id_num.required'  => '证件号 必填',
                    'receiver_email.required'  => '邮箱 必填',
                    'receiver_email.email'     => '不是邮箱格式',
                    'receiver_mobile.required' => '电话 必填',
                    'receiver_mobile.regex'    => '电话号 格式错误',
                ]
            );

            if ($validator->fails()) {
                $error      = collect($validator->errors()->all());
                $returnData = array(
                    'code'  => '0',
                    'msg'   => '验证失败',
                    'data'  => $validator->errors()->first(),
                    'error' => $error->toJson(),

                );

                return response()->json($returnData, 500);
            }

            $member = auth('admin')->user();
            //验证成功

            //查询 消费订单  (可开发票金额)

            //是否符合开票金额


            //创建申请
            $invoice_data = [
                'user_id'              => $member->id,
                'invoice_type'         => 2,  //1个人  2增值税普通发票   3增值税专用发票
                'invoice_content_type' => 2,  //发票内容 1:商品明细 2:网络服务费
                'invoice_amount'       => $request->get('invoice_amount'),
                'invoice_title'        => $request->get('invoice_title'),
                'invoice_id_num'       => $request->get('invoice_id_num'),
                'receiver_email'       => $request->get('receiver_email'),
                'receiver_mobile'      => $request->get('receiver_mobile'),
            ];
            //dd($invoice_data);

            $is_create = Invoice::create($invoice_data);
            if ($is_create) {
                return $this->result_api(200, 'success');
            } else {
                return $this->result_api(200, '提交失败');
            }
        }

        return view('member.funds.invoice');
    }

    public function invoiceList(Request $request)
    {
        if ($request->isMethod('POST')) {
            $status = $request->get('status');
            $value  = $request->get('value');
            $limit  = $request->get('limit', 10);
            $data   = Invoice::orderby('created_at', 'DESC')->
            where(function ($query) use ($value) {
                $query->where('invoice_title', 'like', '%'.$value.'%')
                      ->orWhere('invoice_id_num', 'like', '%'.$value.'%');
            })->
            where('status', $status == null ? '!=' : '=', $status)->
            where('user_id', auth('admin')->user()->id)->
            paginate($limit);

            $count = $data->total();
            if ($data) {
                return response()->json(['code' => 0, 'msg' => 'ok', 'count' => $count, 'data' => $data]);
            } else {
                return $this->result_api(200, 'list error');
            }
        }

        return view('member.funds.invoice-list');
    }
}
